#!/bin/bash
uprio=(0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0)
upwio=(0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0)
timeuprio=(0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0)
timeupwio=(0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0)

lockfile='/tmp/lich_monitor.lock'
if [ ! -f "$lockfile" ]; then
    touch "$lockfile"
else
    exit
fi

basepath=$(cd `dirname $0`; pwd)

while true
do
    if [ $1 == stop ]; then
        break;
    fi

    lichdev=`lich.node --disk_list |grep -v writeback |awk '{print $2$3}' |grep -v ^$| grep -v HDD| grep -v SSD| grep -v NVMe | cut -d '/' -f 3`
    if [ -z "$lichdev" ]
    then
	    sleep 5
	    continue
    fi

    cachedev=`lich.node --disk_list |grep writeback |awk '{print $2$3}' |grep -v "^$" | cut -d '/' -f 3`
    if [ -z "$cachedev" ]
    then
	    sleep 5
	    continue
    fi

    poolinfo=`lich.node --disk_list |grep -v "^/dev" |awk '{print $3}'|grep -v "^$" |sort -u`
    if [ -z "$poolinfo" ]
    then
	    sleep 5
	    continue
    fi

	j=0
	for i in  $lichdev 
	do
		#echo " $j : dev: $i, total read ${upwio[$j]}, total write ${uprio[$j]}"
		rio=$(grep "${i:0:3}" /proc/diskstats |awk '{print $4}')
		wio=$(grep "${i:0:3}" /proc/diskstats |awk '{print $8}')
		
		#echo "dev: $i, total read ${uprio[$j]}, newread $rio, total write ${upwio[$j]}, newwrite $wio" 	
		timeuprio[$j]=`expr $rio - ${uprio[$j]}`
		timeupwio[$j]=`expr $wio - ${upwio[$j]}`
		#echo "dev: $i  Read : $Real_rio Write : $Real_wio"
		uprio[$j]=$rio
		upwio[$j]=$wio

		let j++
	done

	for i in $poolinfo
	do
		#echo pool $i
		totalread=0
		totalwrite=0
		
		k=0
		for j in $lichdev
		do
			if [ "$i" == "${j:3:50}" ]
			then
				totalread=`expr $totalread + ${timeuprio[$k]}`
				totalwrite=`expr $totalwrite + ${timeupwio[$k]}`
			fi

			let k++
		done	

		#cal the cache disknr of the pool
		cachecount=0
		for j in $cachedev
		do
			if [ "$i" == "${j:3:50}" ]
			then
				let cachecount++
			fi			
		done
		
		if [ $cachecount -eq 0 ]
		then 
			continue
		fi

		#cal the write read per cache disk
		diskread=`expr $totalread / $cachecount`
		diskwrite=`expr $totalwrite / $cachecount`
		for j in $cachedev
		do
			if [ "$i" == "${j:3:50}" ]
			then
				sh $basepath/write.sh /dev/${j:0:3} $diskwrite &
				sh $basepath/read.sh /dev/${j:0:3} $diskread &
			fi			
		done

	done

	sleep 5
done

lockdev -u /dev/null
